from django.core.exceptions import ObjectDoesNotExist
from django.db.models import Q

from . import getweb, models, general_and_constant


def update_and_check():
    """
    更新开奖信息，并执行中奖检测
    :return:返回字符串，发送普通短信
    """
    getweb._to_sqlite('phasenum')  # 获取最新的开奖信息，并存入数据库

    winning_list = get_winning_info()  # 获取中奖信息
    msg = ''
    if len(winning_list) > 0:

        for winninginfo in winning_list:
            phase_num = winninginfo['phase_num']
            total_bonus = winninginfo['total_bonus']
            note_num = winninginfo['note_num']
            win_note_num = winninginfo["win_note_num"]
            msg = msg + '恭喜！您投注的' + str(phase_num) + '期大乐透,' + '总投注' + str(note_num) + '注,中奖' + str(
                win_note_num) + '注，中奖总额' + str(total_bonus) + '元。'

    return msg


def update_and_check_dict():
    """
       更新开奖信息，并执行中奖检测
       :return:返回字典列表发送参数给模板
       """
    getweb._to_sqlite('phasenum')  # 获取最新的开奖信息，并存入数据库

    winning_list = get_winning_info()  # 获取中奖信息
    return winning_list


def get_winning_info():
    """
    获取中奖信息
    :return: 返回一个字典列表,每个字典包括期数，总中奖金额，投注数，中奖注数
    """
    on_check_phase = models.note_data.objects.filter(ischeck=False).values("phasenum").distinct().order_by("phasenum")#TODO 此处有bug，返回了所有数据，应返回比当前输入期数小的数据，或在修改是否已计算奖励时看看数据库中是否有该期数据

    result_list = []
    for phasenum in on_check_phase:
        phase_num = phasenum["phasenum"]
        # print(phase)

        try:
            phaseinfo = models.phase_data.objects.get(phasenum=phase_num)  # get如查询不到，会抛出doesnoexist异常
        except ObjectDoesNotExist:
            continue  # 不做任何事，直接下一期数据
        lottery = general_and_constant.check_bonus(phase_num)
        note_num = len(lottery)
        first_price = phaseinfo.firstprice
        second_price = phaseinfo.secondprice
        total_bonus = general_and_constant.calculate_bonus(lottery, first_price, second_price)
        lottery = models.note_data.objects.filter(~Q(bonuslevel='未中奖'), phasenum=phase_num)
        if total_bonus > 0:
            winning = {'phase_num': phase_num, 'total_bonus': total_bonus, 'note_num': note_num,
                       'win_note_num': len(lottery)}
            result_list.append(winning)
        else:
            continue
    return result_list
